//
//  MineViewController.swift
//  新浪微博
//
//  Created by yaozhen on 2017/11/27.
//  Copyright © 2017年 ZYZ. All rights reserved.
//

import UIKit


///主控制器
class MineViewController: UITabBarController {
    //定时器 定时刷新
    private var timer : Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpChildControllers()
        setupCompostButton()
        setUpTimer()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: UserShouldLoginNotifaication), object: nil)
        
    }
    deinit{
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: UserShouldLoginNotifaication), object: nil)
    }
    /*
     protrait ：竖屏 ，肖像
     landscape :横屏，风景画
     使用代码控制设置的方向 好处 可以在使用横屏的时候单独处理
     如果播放视频 都是通过model播放的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    @objc private func userLogin(noti:Notification){
        print("通知传递信息用户登录")
        let nav = UINavigationController.init(rootViewController: OAuthViewController())
        present(nav, animated: true, completion: nil)
        
    }
    
    
    //Mark - 监听方法
    //没有实现
    //private  方法私有
    //@objc  允许这个函数在运行时 通过oc被调用
    
    @objc private func composeStatus(){
        print("撰写微博")
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nava = UINavigationController.init(rootViewController: vc)
        present(nava, animated: true, completion: nil)
    }
    
    
    //私有控件
    //撰写按钮
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}
extension MineViewController:UITabBarControllerDelegate{
    //是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//        print("将要切换到\(viewController)")
        let index = (childViewControllers as NSArray).index(of: viewController)
        if selectedIndex == 0 && index == selectedIndex {
            print("点击首页")
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! HomeViewController
            vc.tableView?.setContentOffset(CGPoint.init(x: 0, y: -64), animated: true)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
               vc.loadData()
            })
            
        }
        return !viewController.isMember(of: UIViewController.self)
    }
}



//mark -- 时钟相关方法
extension MineViewController{
    private func setUpTimer(){
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    @objc private func updateTimer(){
        if !NetworkManager.shared.userLogOn {
            return
        }
        
        NetworkManager.shared.unreadCount { (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" :nil
            //设置APP 的badgeNumber 从iOS8.0之后 要用户授权之后才能够显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


//extentsion 切分代码块
//相近代码功能 缝在一个extension
//便于维护
//注意：OC的分类一样 extension中不能定义属性
//MARK： -设置界面
extension MineViewController{
    //设置撰写按钮
    private func setupCompostButton(){
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //将宽度减少 能够让按钮宽度变大 盖住容错点 防止穿帮
        let width = tabBar.bounds.width / count - 1
        //CGRectInset 正数向内缩进 ,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        //监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    //计算按钮的位置
    
    
    
    
    
    
    

    
    //设置所有子控制器
    private func setUpChildControllers(){
        //获取沙河文件路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("demo.json")
        var data = NSData.init(contentsOfFile: jsonPath)
        //判断data是否有内容 如果没有文件从本地加载
        if data == nil {
            let path = Bundle.main.path(forResource: "demo", ofType: "json")
            data = NSData.init(contentsOfFile: path!)
        }
        //data 一定有一个内容 反序列化
        
        //在很多应用程序中，页面创建都需要网络的json
        //fan'xu'lie'hua
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]] else {
            return
        }
        /*
        guard let path = Bundle.main.path(forResource: "demo", ofType: "json"),
        let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String:Any]]
        else {
            return
        }
         */
        //从 bundle 加载配置的json
//        let array:[[String:Any]] = [
//            ["clsName":"HomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人信息"]],
//            ["clsName":"MessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"关注一些人信息--消息"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"DiscoverViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"关注一些人信息---发现"]],
//            ["clsName":"ProfileViewController","title":"我的","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"关注一些人信息----我的"]],
//        ]
        //测试数据格式 是否正确 -- 转换成plist 数据更加直观
//        (array as NSArray).write(toFile: "/Users/sunqichao/Desktop/demo.plist", atomically: true)
        //数组 - >json序列号
//        let data = try? JSONSerialization.data(withJSONObject: array, options: [])
//        (data as? NSData)?.write(toFile:"/Users/sunqichao/Desktop/demo.json" , atomically: true)
        
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
        
    }
    //使用一个子控制器
    private func controller(dict: [String:Any]) -> UIViewController {
       guard let claName = dict["clsName"] as? String,
        let title = dict["title"] as?String,
        let imageName = dict["imageName"] as?String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + claName) as? BaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String:String]
        else {
            
        return UIViewController()
            
        }
        //2 创建视图控制器
        
        let vc  = cls.init()
        vc.title = title
        
        //设置控制器访客信息字典
        vc.visitorInfoDictionary = visitorDict
        //3 设置图片
        vc.tabBarItem.image = UIImage.init(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage.init(named: "tabbar_"+imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //4 设置tabbar 标题
    vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.red,NSAttributedStringKey.font:UIFont.systemFont(ofSize: 12.0)], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)], for: .normal)
        //实例化导航控制器的时候，回调用铺设方法将rootvc 压栈
        let nav = NavagationViewController.init(rootViewController: vc)
        return nav
        
        
        
        
        
    }
}
